package com.alvis.media.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {

    // ✅ 保存路径，与 Python 一致
    private static final String BASE_DIR = "E:/java_qimo/media-analysis-system_1/target/classes/static/uploads/ai-analysis/";

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "{\"message\":\"文件为空\",\"code\":400}";
        }

        try {
            // 防止重名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String fileName = timestamp + "_" + file.getOriginalFilename();
            File dest = new File(BASE_DIR + fileName);

            // 自动创建目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            file.transferTo(dest);

            // ✅ 返回可访问URL
            String accessUrl = "http://localhost:8000/uploads/ai-analysis/" + fileName;
            System.out.println("✅ 上传成功 -> " + accessUrl);
            return accessUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"message\":\"系统内部错误\",\"code\":500}";
        }
    }
}
